import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# 支持中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
# 支持负数
plt.rcParams['axes.unicode_minus'] = False

def create_2d_cartesian_system(x_range=(-5, 5), y_range=(-5, 5), figsize=(8, 6)):
    """
    创建二维直角坐标系
    """
    fig, ax = plt.subplots(figsize=figsize)
    
    # 设置坐标轴范围
    ax.set_xlim(x_range[0], x_range[1])
    ax.set_ylim(y_range[0], y_range[1])
    
    # 设置坐标轴居中
    ax.spines['left'].set_position('zero')
    ax.spines['bottom'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    # 添加箭头
    ax.annotate('', xy=(x_range[1]-0.2, 0), xytext=(x_range[1]-0.8, 0),
                arrowprops=dict(arrowstyle="->", lw=1.2, color='black'))
    ax.annotate('', xy=(0, y_range[1]-0.2), xytext=(0, y_range[1]-0.8),
                arrowprops=dict(arrowstyle="->", lw=1.2, color='black'))
    
    # 设置标签
    ax.text(x_range[1]-0.5, -0.5, 'x', fontsize=14, fontweight='bold')
    ax.text(0.2, y_range[1]-0.5, 'y', fontsize=14, fontweight='bold')
    
    # 设置刻度
    x_ticks = np.arange(x_range[0], x_range[1]+1, 1)
    y_ticks = np.arange(y_range[0], y_range[1]+1, 1)
    ax.set_xticks(x_ticks[x_ticks != 0])
    ax.set_yticks(y_ticks[y_ticks != 0])
    
    # 标记原点
    ax.plot(0, 0, 'ko', markersize=4)
    ax.text(-0.3, -0.5, 'O', fontsize=12, fontweight='bold')
    
    # 添加网格
    ax.grid(True, linestyle='--', alpha=0.7)
    
    ax.set_title('二维直角坐标系', fontsize=16, pad=20)
    
    return fig, ax

if __name__ == "__main__":
    # 1. 二维直角坐标系
    fig1, ax1 = create_2d_cartesian_system()
    # 添加一个示例函数 y = x
    x = np.linspace(-4, 4, 100)
    y = x
    ax1.plot(x, y, 'b-', linewidth=2, label='y = x')
    ax1.legend()
    plt.show()
